package com.spark.common.helper

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Rect
import android.view.View

/**
 * 虚拟按键挡住 tab
 */
class AndroidWorkaround private constructor(var content: View) {
    companion object {
        fun assitActivity(content: View): AndroidWorkaround {
            return AndroidWorkaround(content)
        }

        @SuppressLint("PrivateApi")
        fun checkDeviceHasNav(context: Context): Boolean {
            var hasNav = false
            val resources = context.resources
            val id = resources.getIdentifier("config_showNavigationBar", "bool", "android")
            if (id > 0) hasNav = resources.getBoolean(id)
            try {
                val clazz = Class.forName("android.os.SystemProperties")
                val method = clazz.getMethod("get", String.javaClass)
                val navBarOverrid = method.invoke(clazz, "qemu.hw.mainkeys") as String
                if ("1" == navBarOverrid) hasNav = false
                else if ("0" == navBarOverrid) hasNav = true
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return hasNav
        }
    }

    var childOfContent: View = content
    var framelp = childOfContent.layoutParams
    var usableHeightPre = 0

    init {
        childOfContent.viewTreeObserver.addOnGlobalLayoutListener {
            possibleResizeChildOfContent()
        }
    }

    private fun possibleResizeChildOfContent() {
        val usableHeight = computeUsableHeight()
        if (usableHeight != usableHeightPre) {
            framelp.height = usableHeight
            childOfContent.requestLayout()
            usableHeightPre = usableHeight
        }
    }

    private fun computeUsableHeight(): Int {
        val rect = Rect()
        childOfContent.getWindowVisibleDisplayFrame(rect)
        return rect.bottom
    }
}